package com.longlong.utils;


import com.google.gson.Gson;
import com.longlong.config.WxGzhProperties;
import com.longlong.config.globalExceptionClass.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;


/**
 * 微信验证工具获取微信
 */
@Component
@Slf4j
public class WxLoginUtil {

    /**
     * 获取openid
     */
    public String getOpenid(String code){
        //1.判断code是否合法
        if(StringUtils.isEmpty(code)){
            throw new BusinessException(505,"code不合法");
        }
        //2.通过code获取access_token
        String baseAccessTokenUrl="https://api.weixin.qq.com/sns/oauth2/access_token"+
                "?appid=%s"+
                "&secret=%s"+
                "&code=%s"+
                "&grant_type=authorization_code";
        String accessTokenUrl = String.format(baseAccessTokenUrl, WxGzhProperties.WX_OPEN_APP_ID, WxGzhProperties.WX_OPEN_APP_SECRET,code);
        String result = null;
        try {
            //1.执行请求
            result = new HttpClientUtils().get(accessTokenUrl);
            System.out.println("获取服务器请求");
            System.out.println(result);
            //3.对微信返回的数据进行转换
            Gson gson = new Gson();
            Map<String, Object> resultMap = gson.fromJson(result, HashMap.class);
            if(resultMap.get("errcode") !=null ){
                throw new BusinessException(505,"请求错误");
            }
            //4.解析微信用户的唯一凭证openid
            String openid = (String)resultMap.get("openid");
            if(StringUtils.isEmpty(openid)){
                log.error("解析openid失败");
                throw new BusinessException(505,"解析openid失败");
            }
            return openid;
        }catch (Exception e){
            log.error("解析openid失败");
            throw new BusinessException(505,"解析openid失败");
        }
    }
}
